<template>
  <div class="container">
    <el-row class="page">
      <el-col :span="16" align="left">
        <el-input v-model="data.params.name" placeholder="标准名称" style="width: 150px; margin-right: 15px" />
        <SelectOption :options="data.orgAllList" :placeholder="'标准级别'" @change-value="changeValue1"> </SelectOption>
<!--
          <SelectOption :options="data.typeOptions" :placeholder="'标准类别'" :selectValue="data.typeValue"
            @change-value="changeValue2"> </SelectOption>
-->
        <el-button class="ordinary" @click="search()">搜索</el-button>
      </el-col>
      <el-col :span="8" align="right">
        <el-button class="unlock" @click="getUnlockBtn()" v-limit="'KJSL:HYBZHGX:JSBZ:UNLOCK'">解锁</el-button>
        <el-button class="lock" @click="getLockBtn()" v-limit="'KJSL:HYBZHGX:JSBZ:LOCK'">锁定</el-button>
        <el-button class="ordinary" @click="getExportBtn()"  v-limit="'KJSL:HYBZHGX:JSBZ:EXPERT'">批量导出</el-button>
        <el-button type="danger" @click="handleDetect()" v-limit="'KJSL:HYBZHGX:JSBZ:DELETE'">批量删除</el-button>
        <el-button type="primary" @click="handleAdd()" v-limit="'KJSL:HYBZHGX:JSBZ:ADD'">新增</el-button>
      </el-col>
    </el-row>
    <div>
      <Table :loading="data.loading" :tableArr="data.allTableData"
             :dblclick="(row) => handleEdit(row)"
             :pagination="data.page" :columns="data.columns" :total="data.page.total"
             @selectItem="getCurrentList" @delectTable="delectIds" @currentChange="handleCurrentChange" @sizeChange="handleSizeChange">
        <template #status="{ row }">
          <span v-if="row.isLock == 1">已锁定</span>
          <span v-else>
            <span style="color: #FFC783" v-if="row.status == '待确认'">待确认</span>
            <span style="color: #B5F1FF" v-if="row.status == '已确认'">已确定</span>
            <span style="color: #B5F1FF" v-if="row.status == '正常'">正常</span>
          </span>
        </template>
        <template #operate="{ row }">
          <el-button size="small" class="ordinary" v-show="row.updateFlag" :key="row.id + 'bj'" :disabled="row.isLock == 1"  v-limit="'KJSL:HYBZHGX:JSBZ:EDIT'"
            @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" class="ordinary"  @click="handleDetail(row)">详情</el-button>
          <el-button v-if="row.status == '待确认'" size="small" type="primary" :key="row.id + 'qr'"  v-limit="'KJSL:HYBZHGX:JSBZ:CONFIRM'"
            :disabled="row.isLock == 1" @click="handleConfirm(row)">确认</el-button>
        </template>
      </Table>

    </div>

    <el-dialog v-model="data.dialogVisible" width="60%" top="10vh" :show-close="false" :close-on-click-modal="false"
      @closed="handleCloseDialog()">
      <template #title>
        <div class="my-header" v-loading="data.detail_loading">
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane label="基本信息" name="1">
              <Information :currentEdit="data.currentEdit" v-if="data.dialogVisible" ref="getAssociation"  @valueFlag="valueFlag"></Information>
            </el-tab-pane>
            <el-tab-pane label="主编单位" name="2">
              <Members v-if="data.dialogVisible" :members="data.members" :membersFlag="data.membersFlag" @paramsChange="paramsChange"></Members>
            </el-tab-pane>
            <el-tab-pane label="参编单位" name="3">
              <Members v-if="data.dialogVisible" :members="data.participatingUnits" :membersFlag="data.membersFlag"
                @paramsChange="participatingChange"></Members>
            </el-tab-pane>
            <el-tab-pane label="编写人员" name="4">
              <Write v-if="data.dialogVisible" :members="data.writers" :membersFlag="data.writeFlag" @paramsChangeInMember="paramsChangeInMember" :inMember="data.inMember" :outMember="data.outMember"
                @paramsChangeOutMember="paramsChangeOutMember">
              </Write>
            </el-tab-pane>
            <el-tab-pane label="相关附件" name="5">
              <platformFiles :filesTypeFlag="false" :files="data.files" @dataChange="dataChange"
                @filesParams="filesParams"  download="KJSL:HYBZHGX:JSBZ:DOWNLOAD"  upload="KJSL:HYBZHGX:JSBZ:UPLOAD" fileDelete="KKJSL:HYBZHGX:JSBZ:FILEDELETE"></platformFiles>
            </el-tab-pane>

            <el-tab-pane label="变更记录" name="6" v-if="data.addFlag == 1">
              <Record :changeLogs="data.changeLogs"></Record>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDialog">关闭</el-button>
          <el-button type="primary" @click="handleSave()">保存</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="data.detailVisible" width="60%" top="10vh" :show-close="false" :close-on-click-modal="false"
      @closed="handleCloseDialog()">
      <template #title>
        <div class="my-header" v-loading="data.detailVisible_loading">
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane label="基本信息" name="1">
              <Information :currentEdit="data.currentEdit" ref="getAssociation" v-if="data.detailVisible" @valueFlag="valueFlag"></Information>
            </el-tab-pane>
            <el-tab-pane label="主编单位" name="2">
              <Membersxq :members="data.members" :membersFlag="data.membersFlag" @paramsChange="paramsChange"></Membersxq>
            </el-tab-pane>
            <el-tab-pane label="参编单位" name="3">
              <Membersxq :members="data.participatingUnits" :membersFlag="data.membersFlag"
                @paramsChange="participatingChange"></Membersxq>
            </el-tab-pane>
            <el-tab-pane label="编写人员" name="4">
              <Writexq :members="data.writers" :membersFlag="data.writeFlag" @paramsChangeInMember="paramsChangeInMember" :inMember="data.inMember" :outMember="data.outMember"
                @paramsChangeOutMember="paramsChangeOutMember">
              </Writexq>
            </el-tab-pane>
            <el-tab-pane label="相关附件" name="5">
              <platformFilesxq :filesTypeFlag="false" :files="data.files" @dataChange="dataChange"
                @filesParams="filesParams"  download="KJSL:HYBZHGX:JSBZ:DOWNLOAD"  upload="KJSL:HYBZHGX:JSBZ:UPLOAD" fileDelete="KKJSL:HYBZHGX:JSBZ:FILEDELETE"></platformFilesxq>
            </el-tab-pane>

            <el-tab-pane label="变更记录" name="6" v-if="data.addFlag == 1">
              <Record :changeLogs="data.changeLogs"></Record>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import * as proxy from '@/constants/proxy';
import request from '@/utils/request';
import SelectOption from '@/views/science/components/selectOption/index.vue';
import Table from "@/views/science/components/table/TableDate.vue";
import { onMounted, reactive, ref } from 'vue';
import Information from './information.vue';
import Informationxq from './informationxq.vue';
import Members from './members.vue';
import Membersxq from './membersxq.vue';
import tableData from './tableHeader.json';
import Write from './write.vue';
import Writexq from './writexq.vue';
// import Association from '@/views/science/construction/high-end-platform/association.vue'
import platformFiles from '@/views/science/components/platformFiles/platformFiles.vue';
import platformFilesxq from '@/views/science/components/platformFiles/platformFilesxq.vue';
import Record from "@/views/science/components/record/record.vue";
import { Modals, tips } from '@/views/science/components/tips/tips';
// import { validatePhoneNumber } from '@/utils/util'
import { useStore } from 'vuex';
import { getAdd, getConfirm, getDelect, getDetail, getExport, getList, getLock, getUnlock, getUpdate } from '../../api/technicalNorms';
import {getExport2} from "@/views/science/api/patent";
import { ElMessage } from 'element-plus';
// import { setup } from 'vue-class-component'
export default {
  name: 'technicalNorms',
  components: {
    SelectOption,
    Table,
    Information,
    Members,
    Write,
    Informationxq,
    Membersxq,
    Writexq,
    Record,
    // Association,
    platformFiles,
    platformFilesxq,
  },
  setup() {
    const store = useStore()
    const activeName = ref('1')
    const pagination = reactive({  //分页器信息
      pageSize: 10,
      currentPage: 1,
    })
    const data = reactive({
      addFlag: 0,
      currentEdit:true,
      changeLogs: [],
      unit: [],
      dialogVisible: false,
      recordShow: false,
      loading: false,
      detail_loading:false,
      page: { page: 1, limit: 10, total: 0 },

      params: {
        name: '',
        levelName: '',
        level: '',
        normType: '',
        mainUnit: '',
        enterpriseRanking: '',
        current: 1,
        size: 10,
        id: '',
        levelId: '',
        classId: '',
        proType: '',
      },
      inMember: [],
      outMember: [],
      selectedRows: [] as any,
      columns: tableData.platformTableHeader,
    // {
    //   "key": "classType",
    //     "width": 140,
    //     "label": "标准类别"
    // },

      ids: [],
      allTableData: [],
      files: [],
      flag: null,
      members: [],
      membersFlag: false,
      writeFlag: false,
      writers: [],
      participatingUnits: [],
      information: [],
      undertakeUnitId: '',
      undertakeUnit: '',
      orgAllList: [],
      typeOptions: [],
      typeValue: '',
      detailVisible_loading:false,
      detailVisible: false,
    })
    //详情数据获取
    const detailVisibleData = async (id) => {
      data.detailVisible_loading = true
      let res = await getDetail(id)
      if (res.data.success) {
        const arr = res.data.data.info
        store.commit('technicalNorms/getForm', { ...arr })
        data.information = res.data.data.info
        data.members = res.data.data.chiefUnits
        data.membersFlag = true

        data.participatingUnits = res.data.data.participatingUnits
        data.files = res.data.data.files
        data.changeLogs = res.data.data.operLog
        data.inMember = res.data.data.inMember
        data.outMember = res.data.data.outMember

        data.writeFlag = true

        data.undertakeUnitId = res.data.data.undertakeUnitId
        data.undertakeUnit = res.data.data.undertakeUnit

        data.detailVisible = true
        data.addFlag = 1
        data.detailVisible_loading = false
      }else{
        data.detailVisible_loading = false
      }

    }
    const handleDetail = (row) => {
      data.currentEdit = false
      data.detailVisible = true
      data.addFlag = 1
      store.commit('technicalNorms/getRowId', row.id)
      detailVisibleData(row.id)
    }

    const handleClose = () => {
      data.detailVisible = false
      data.recordShow = false;
      activeName.value = '1'
      data.members = []
    }

    // 搜索
    const search = () => {
      data.page.page = 1
      console.log(data.params)
      tableList()
    }
    // 搜索change
    const changeValue = (item) => data.params.levelName = item.id
    const changeValue1 = (item) => {
      if (item) {
        data.params.levelId = item.itemValue
      } else {
        data.params.levelId = ''
      }
      data.typeOptions = item.children
      data.params.proType = ''
      data.typeValue = ''
    }
    const changeValue2 = (item) => {
      data.params.classId = item.itemValue
      data.typeValue = item.itemText
    }
    const getCurrentList = (currentList) => {
      console.log(currentList, 'getCurrentList')
      data.selectedRows = currentList
    }
    const delectIds = (ids) => {
      data.params.id = ids
    }

    //主页面表格初始化
    const tableList = async () => {
      data.loading = true
      data.params.size = pagination.pageSize
      data.params.current = pagination.currentPage
      data.params.id = ''

      let res = await getList(data.params)
      if (res.data.success) {
        let records = res.data.data
        records.records.map((item) => {
          if (item.status == 0) {
            item.status = "待确认"
          } else {
            item.status = "已确认"
          }
        })
        data.allTableData = res.data.data.records
        data.page.total = records.total
        data.loading = false
      }else{
        data.loading = false
      }
    }

    // 内部人员


    let paramsChangeInMember = (params) => {

      data.writeFlag = false;

      data.inMember = params
    }


    // 外部人员
    let paramsChangeOutMember = (params) => {

      data.writeFlag = false;

      data.outMember = params
    }
    //解锁
    const getUnlockBtn = async () => {
      if (data.params.id.length) {
        Modals('是否解锁选择内容', '提示', 'warning').then(async () => {
          let res = await getUnlock(data.params.id)
          if (res.data.success) {
            tips('解锁成功', 'success')
            tableList()
          }
        }).catch(() => {
          console.log("点击了取消")
        })
      } else {
        tips('请选择', 'warning')
      }
    }
    //锁定
    const getLockBtn = () => {
      if (data.params.id.length) {
        let flag = true
        console.log(data.selectedRows, 'selectedRows')
        data.selectedRows.forEach((obj) => {
          if (obj.status == '待确认') {
            flag = false
          }
        })
        if (!flag) {
          ElMessage({
            message: '请确认后再进行锁定',
            type: 'warning',
          })
          return
        }
        Modals('是否锁定选择内容', '提示', 'warning').then(async () => {
          let res = await getLock(data.params.id)
          console.log(data.params.id);
          if (res.data.success) {
            tips('锁定成功', 'success')
            tableList()
          }
        }).catch(() => {
          console.log("点击了取消")
        })
      } else {
        tips('请选择', 'warning')
      }
    }
    //导出功能
    const getExportBtn = async () => {

      Modals('是否导出所选数据或者全部数据', '提示', 'warning').then(async () => {

        let tupm ;
        if(data.params.id.length==0){
          tupm = []
        }else {
          //str.join(',')
          tupm = data.params.id;
        }
        await getExport({
          name: data.params.name || '',
          levelId: data.params.levelId || '',
          classId: data.params.classId || '',
          ids:tupm,
        })


      }).catch(() => {
        console.log("点击了取消")
      })
    }
    //批量删除
    const handleDetect = async () => {
      if (data.params.id) {
        Modals('是否删除选择内容', '提示', 'warning').then(async () => {
          let res = await getDelect(data.params.id)
          data.params.id = ''

          if (res.data.success) {
            tips('删除成功', 'success')
            tableList()
          }
        }).catch(() => {
          console.log("点击了取消")
        })
      } else {
        tips('请选择', 'warning')
      }
    }
    //新增
    const handleAdd = () => {
      data.currentEdit = true
      data.dialogVisible = true
      data.addFlag = 0
      data.members = []
      data.information = []
      data.participatingUnits = []
      data.inMember=[]
      data.outMember=[]
      data.writers = []
      data.files = []
      store.commit('technicalNorms/emptyForm')
    }
    //编辑
    const handleEdit = (row) => {
      data.currentEdit = true
      data.dialogVisible = true
      data.addFlag = 1
      store.commit('technicalNorms/getRowId', row.id)
      detailData(row.id)
    }
    //详情数据获取
    const detailData = async (id) => {
      data.detail_loading = true
      let res = await getDetail(id)
      if (res.data.success) {
        const arr = res.data.data.info
        store.commit('technicalNorms/getForm', { ...arr })
        data.information = res.data.data.info
        data.members = res.data.data.chiefUnits
        data.membersFlag = true

        data.participatingUnits = res.data.data.participatingUnits
        data.files = res.data.data.files
        data.changeLogs = res.data.data.operLog
        data.inMember = res.data.data.inMember
        data.outMember = res.data.data.outMember

        data.writeFlag = true

        data.undertakeUnitId = res.data.data.undertakeUnitId
        data.undertakeUnit = res.data.data.undertakeUnit

        data.dialogVisible = true
        data.addFlag = 1
        data.detail_loading = false
      }else{
        data.detail_loading = false
      }
    }
    //编辑
    const handlhandleEditeAdd = () => {
      data.dialogVisible = true
      data.addFlag = 1
    }
    //查看

    let handleConfirm = async (row) => {

      Modals("是否确认当前流程", "提示", "warning")
        .then(async () => {
          let res = await getConfirm({ id: row.id, status: '1' });
          if (res.data.success) {
            tableList()
          }
        })
        .catch(() => { });
    };


    // 字典
    const affiliation = () => {
      request({
        url: proxy.CHECC_API_CMS + '/dictItem/codelist',
        method: 'post',
        data: ["KJSL_STANDARD_LEVEL_CATEGORY", "KJSL_PREPARATION_CATEGORY"]
      }).then((res) => {
        data.orgAllList = res.data.data.KJSL_STANDARD_LEVEL_CATEGORY
      })
    }
    const dataChange = () => {

      detailData(store.state.technicalNorms.rowId)
    }
    const valueFlag = (flag) => {
      data.flag = flag
    }
    //分页操作
    const handleSizeChange = (val) => {

      pagination.pageSize = val

      tableList()
    }

    const handleCurrentChange = (val) => {

      pagination.currentPage = val

      tableList()
    }
    //主编单位组件 传来的
    const paramsChange = (val) => {
      console.log('主编单位组件 传来的', val);
      data.membersFlag = false
      data.members = val
    }
    //参编单位组件 传来的
    const participatingChange = (val) => {
      console.log('参编单位组件 传来的', val);
      data.membersFlag = false
      data.participatingUnits = val
    }
    //编写人员组件 传来的
    const getAssociation = ref()
    // 保存
    const handleSave = async () => {
      const form = store.state.technicalNorms.form

      form.projectChanger = form.projectChangerName //项目负责人手动输入 没有id
      form.effectDate = form.effectDate ? form.effectDate : null
      form.startDate = form.startDate ? form.startDate : null
      form.endDate = form.endDate ? form.endDate : null
      form.failureDate = form.failureDate ? form.failureDate : null


      // let participatingUnits = []
      // let inMember = []
      // let outMember = []
      // let files = []

      const params = {
        // baseInfo:form,
        // memberList: data.members,
        // fileList: data.files,
        projectList: data.participatingUnits,
        writerList: data.writers,

        info: form,
        chiefUnits: data.members,//主编单位
        participatingUnits: data.participatingUnits,//参编单位
        inMember: data.inMember, //内部人员
        outMember: data.outMember,
        files: data.files,
      }
      console.log('params', params);

      getAssociation.value.submitForm()
      if (!data.flag) {
        return tips('请将基本信息补充完整', 'warning')
      }

      let res
      if (data.addFlag == 0) {
        res = await getAdd(params)
      } else {
        res = await getUpdate(params)
      }
      if (res.data.success) {
        data.dialogVisible = false
        activeName.value = '1'
        tableList()
        data.membersFlag = false
      }

    }
    // 关闭
    const handleCloseDialog = () => {
      data.dialogVisible = false;
      data.recordShow = false;
      activeName.value = '1'
      data.members = []
    }
    //编写人员弹窗
    const projectParams = () => {

    }
    //上传附件
    const filesParams = (params) => {
      data.files = params
    }
    tableList()
    onMounted(() => {
      affiliation();
    });
    return {
      store,
      activeName,
      data,
      paramsChangeInMember,
      paramsChangeOutMember,
      tableList,
      getCurrentList,
      delectIds,
      changeValue,
      changeValue1,
      changeValue2,
      search,
      getUnlockBtn,
      getLockBtn,
      getExportBtn,
      handleDetect,
      handleAdd,
      handleEdit,
      handlhandleEditeAdd,
      handleConfirm,
      handleCloseDialog,
      handleSave,
      dataChange,
      valueFlag,
      getAssociation,
      pagination,
      handleSizeChange,
      handleCurrentChange,
      filesParams,
      affiliation,

      paramsChange,
      participatingChange,
      handleDetail, //详情
      handleClose, //详情
    }
  }
}
</script>

<style lang="scss">
.table_ {
  .el-pagination {
    display: none;
  }
}
</style>

<style scoped lang="scss">
.example-pagination-block {
  margin-top: 15px;
  text-align: center;
}

:deep(.el-pagination .btn-next .el-icon) {
  margin: 0 auto;
}


.container {
  background-color: white;
  padding: 20px;
}

// :deep(.el-dialog__body) {
//   padding: 0 !important
// }
:global(.el-dialog__body) {
  padding: 0;
}

.dialogCloseBtn {
  position: absolute;
  top: 20px;
  right: 20px;
}

// .el-col {
//   line-height: 60px;
// }

.pageName {
  font-weight: 700;
}

.el-form-item {
  .el-input {
    width: 100px;
  }

  .el-select {
    width: 100px;
  }
}

:deep(.demo-tabs>.el-tabs__content) {
  max-height: 500px;
  overflow-y: scroll;
  scrollbar-width: none;
  /* Firefox */
  -ms-overflow-style: none;
  /* IE 10+ */
}

:deep(.demo-tabs>.el-tabs__content::-webkit-scrollbar) {
  display: none;
  /* Chrome Safari */
}

.filesPane {}
</style>
